/**调拨出区汇总清单-清单汇总*/
import {
  PlusOutlined,
  DeleteOutlined,
  SendOutlined,
  CopyOutlined,
  PrinterOutlined,
  ExportOutlined, ImportOutlined,
} from '@ant-design/icons';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, message, Modal } from 'antd';
import { history } from 'umi';
import { useRef, useState } from 'react';
const { confirm } = Modal;
import { ExclamationCircleOutlined } from '@ant-design/icons';

import CreateForm from './components/CreateForm';
import Detail from './components/Detail';
import type { TableListItem, TableBodyListItem } from '@/services/bulkCargo/fpdbAllocEntryHead/typings';
import { pageList } from '@/services/bulkCargo/fpdbAllocEntryHead/service';
import { getParamList, getParams } from '@/services/ant-design-pro/param';
import BillSummaryForm from './components/BillSummaryForm';

const handleAdd = async (record: TableBodyListItem) => {
  console.log(record);
  const hide = message.loading('正在添加');
  try {
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

//申报确认
function declareConfirm(rows: TableListItem[]) {
  console.log(rows);
  confirm({
    title: '提示',
    icon: <ExclamationCircleOutlined />,
    content: '确定要进行申报吗?',
    onOk() {
      console.log('OK');
    },
    onCancel() {
      console.log('Cancel');
    },
  });
}

//复制确认
function copyConfirm(rows: TableListItem[]) {
  console.log(rows);
  confirm({
    title: '提示',
    icon: <ExclamationCircleOutlined />,
    content: '确定要进行复制当前记录吗?',
    onOk() {
      console.log('OK');
      message.success('操作成功');
    },
    onCancel() {
      console.log('Cancel');
    },
  });
}

//删除确认
function deleteConfirm(rows: TableListItem[]) {
  console.log(rows);
  confirm({
    title: '提示',
    icon: <ExclamationCircleOutlined />,
    content: '确定要删除记录吗?',
    onOk() {
      console.log('OK');
      message.success('操作成功');
    },
    onCancel() {
      console.log('Cancel');
    },
  });
}

//批量撤销
function invalidConfirm(rows: TableListItem[]) {
  console.log(rows);
  confirm({
    title: '提示',
    icon: <ExclamationCircleOutlined />,
    content: '确定要进行撤销吗?',
    onOk() {
      console.log('OK');
      message.success('操作成功');
    },
    onCancel() {
      console.log('Cancel');
    },
  });
}



export default () => {
  const index  = history.location.pathname.lastIndexOf('/') + 1;
  const pageType = history.location.pathname.substring(index);
  // 调拨类型
  const allocationType = history.location.pathname.substring(index-3, index-1);
  //console.log(allocationType);
  const actionRef = useRef<ActionType>();
  /**调拨出区汇总清单-清单汇总-弹窗显示*/
  const [billSummaryFormVisible, setBillSummaryFormVisible] = useState<boolean>(false);
  /**选中行(多选)*/
  const [selectedRows, setSelectedRows] = useState<TableListItem[]>([]);
  /**新建窗口的弹窗*/
  const [modalFormVisible, setFodalFormVisible] = useState<boolean>(false);
  /**详情是否显示*/
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  /**赋值双击行数据*/
  const [doubleClickRowRecord, setDoubleClickRowRecord] = useState<TableListItem>();

  const columns: ProColumns<TableListItem>[] = [
    {
      dataIndex: 'index',
      valueType: 'index',
      width: 30,
      align: 'center',
    },
    {
      title: '操作',
      width: 'search' == pageType?170:120,
      align: 'center',
      valueType: 'option',
      //hideInTable: 'search' == pageType,
      render: (text, record, _, action) => [
        'change' == pageType && (<a
          key="change"
          onClick={() => {
            //declareConfirm();
          }}
        >
          修改
        </a>),
        'declare' == pageType && (<a
          key="copy"
          onClick={() => {
            //
          }}
        >
          复制
        </a>),
        ('declare' == pageType || 'change' == pageType) && (<a
          key="declare"
          onClick={() => {
            const rows: TableListItem[] = [];
            rows.push(record);
            declareConfirm(rows);
          }}
        >
          申报
        </a>),
        'declare' == pageType && (<a
          key="delete"
          onClick={() => {
            const rows: TableListItem[] = [];
            rows.push(record);
            deleteConfirm(rows);
          }}
        >
          删除
        </a>),
        'invalid' == pageType && (<a
          key="invalid"
          onClick={() => {
            //
          }}
        >
          撤销
        </a>),
        'summary' == pageType && (<a
          key="summary"
          onClick={() => {
            setBillSummaryFormVisible(true);
          }}
        >
          清单汇总
        </a>),
        'search' == pageType && (<a
          key="summary"
          onClick={() => {
            //数据重发
          }}
        >
          数据重发
        </a>),
        'search' == pageType && (<a
          key="summary"
          onClick={() => {
            //回执重发
          }}
        >
          回执重发
        </a>),
      ],
    },
    {
      title: '预录入号',
      dataIndex: 'preEntryNo',
      width: 180,
      align: 'center',
      order: 10,
    },
    {
      title: '申请单编号',
      dataIndex: 'allocationNo',
      width: 160,
      align: 'center',
      order: 9,
    },
    {
      title: '账册编号',
      dataIndex: 'enterpriseBooksNo',
      width: 120,
      align: 'center',
      hideInTable: 'summary' != pageType,
      order: 1,
    },
    {
      title: '调拨类型',
      dataIndex: 'allocationType',
      width: 120,
      align: 'center',
      valueType: 'select',
      request: () => getParamList('allocationType'),
      hideInSearch: ['declare','summary'].includes(pageType),
      hideInTable: ['declare','summary'].includes(pageType),
      order: 3,
    },
    {
      title: '经营企业名称',
      dataIndex: 'tradeName',
      width: 250,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '启运区块',
      dataIndex: 'departureBlock',
      width: 100,
      align: 'center',
      valueType: 'select',
      request: () => getParamList('blockCode'),
      initialValue: '',
      order: 8,
    },
    {
      title: '目的区块',
      dataIndex: 'destinationBlock',
      width: 100,
      align: 'center',
      valueType: 'select',
      request: () => getParamList('blockCode'),
      initialValue: '',
      order: 7,
    },
    {
      title: '审核状态',
      dataIndex: 'stepId',
      width: 120,
      align: 'center',
      valueType: 'select',
      request: () =>
      pageType=='declare'?getParams('approveStatus',['FPDBJJRQ100100','FPDBJJRQ100200','FPDBJJRQ100600']):
      pageType=='change'?getParams('approveStatus',['FPDBJJRQ100990','FPDBJJRQBG100200','FPDBJJRQBG100500','FPDBJJRQBG100600']):
      (pageType=='invalid' || pageType=='summary')?getParams('approveStatus',['FPDBJJRQ100990']):
      getParamList('approveStatus'),
      order: 6,
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      width: 150,
      align: 'center',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '申报日期',
      dataIndex: 'declareDate',
      width: 150,
      align: 'center',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '审批时间',
      dataIndex: 'approveDate',
      width: 150,
      align: 'center',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createDateS',
      width: 260,
      align: 'center',
      valueType: 'dateRange',
      hideInTable: true,
      order: 5,
    },
    {
      title: '申报时间',
      dataIndex: 'declareDateS',
      width: 260,
      align: 'center',
      valueType: 'dateRange',
      hideInTable: true,
      order: 4,
    },
    {
      title: '区分标志',
      dataIndex: 'mark',
      width: 120,
      align: 'center',
      hideInSearch: pageType != 'search',
      hideInTable: pageType != 'search',
      valueType: 'select',
      valueEnum: {
        1: { text: ' ' },
      },
      order: 2,
    },
    {
      title: '子清单编号',
      dataIndex: 'childListNO',
      width: 120,
      align: 'center',
      hideInTable: true,
      hideInSearch: pageType != 'summary',
      order: 0,
    },
  ];

  const listTable = (
    <>
      <ProTable<TableListItem>
        columns={columns}
        actionRef={actionRef}
        /* request={pageList} */
        request={async (params, sort, filter) => {
          params['pageType'] = pageType;
          params['allocationType'] = 'in'==allocationType?'1':2;//调拨类型
          console.log(params, sort, filter);
          return pageList(params)
        }}
        pagination={{
          pageSize: 10,
        }}
        bordered
        scroll={{
          x: 2000,
        }}
        rowSelection={{
          onChange: (_, selectedRow) => {
            setSelectedRows(selectedRow);
          },
        }}
        tableAlertRender={false}
        search={{
          labelWidth: 100,
        }}
        rowKey="id"
        toolBarRender={() => [
          'declare' == pageType && (
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                setFodalFormVisible(true);
              }}
            >
              录入
            </Button>
          ),
          'declare' == pageType && <Button icon={<ImportOutlined />}>导入</Button>,
          ('declare' === pageType || 'change' == pageType) && (
            <Button
              key="button"
              icon={<SendOutlined />}
              type="primary"
              disabled={selectedRows.length == 0}
              onClick={() => {
                declareConfirm(selectedRows);
              }}
            >
              申报
            </Button>
          ),
          'declare' == pageType && (
            <Button
              key="button"
              icon={<CopyOutlined />}
              type="primary"
              disabled={selectedRows.length == 0}
              onClick={() => {
                copyConfirm(selectedRows);
              }}
            >
              复制
            </Button>
          ),
          'declare' == pageType && (
            <Button
              key="button"
              icon={<DeleteOutlined />}
              danger
              disabled={selectedRows.length == 0}
              onClick={() => {
                deleteConfirm(selectedRows);
              }}
            >
              删除
            </Button>
          ),
          'invalid' == pageType && (
            <Button
              key="button"
              icon={<SendOutlined />}
              type="primary"
              disabled={selectedRows.length == 0}
              onClick={() => {
                invalidConfirm(selectedRows);
              }}
            >
              撤销
            </Button>
          ),
          <Button icon={<ExportOutlined />}>导出</Button>,
          <Button icon={<PrinterOutlined />}>打印</Button>,
        ]}
        onRow={(record) => {
          return {
            //onClick: (event) => {}, // 点击行
            onDoubleClick: () => {
              if(pageType == 'summary'){
                setBillSummaryFormVisible(true);
              }else{
                setDoubleClickRowRecord(record);
                setDetailVisible(true);
              }
            },
            //onContextMenu: (event) => {},
            //onMouseEnter: (event) => {}, // 鼠标移入行
            //onMouseLeave: (event) => {},
          };
        }}
      />

      <CreateForm
        id={''}
        modalVisible={modalFormVisible}
        onSubmit={async (record) => {
          const success = await handleAdd(record);
          if (success) {
            setFodalFormVisible(false);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setFodalFormVisible(false);
        }}
      />
      <BillSummaryForm
        modalVisible={billSummaryFormVisible}
        onCancel={() => {
          setBillSummaryFormVisible(false);
        }}
      />


    </>
  );

  if (!detailVisible) {
    return listTable;
  } else {
    return (
      <Detail
        record={doubleClickRowRecord}
        onBack={() => {
          setDetailVisible(false);
        }}
      />
    );
  }
};
